package com.suzhuoke.ncpsy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.suzhuoke.ncpsy.api.CommonResult;
import com.suzhuoke.ncpsy.api.ResultCode;
import com.suzhuoke.ncpsy.model.*;
import com.suzhuoke.ncpsy.service.TpService;
import com.suzhuoke.ncpsy.util.sha.SHA256Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @author 乔宏展
 * CreateTime 2020/6/22 14:39
 */
@Api(tags = "TpController", description = "溯源模板Controller")
@Controller
public class TpController {
    @Resource
    private TpService tpService;
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    @ModelAttribute
    public void preHandler(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
    }

    @RequestMapping(value = "/addTp", produces = "application/json;charset=utf-8",method = RequestMethod.POST)
    @ApiOperation("添加溯源模板")
    @ResponseBody
    @Transactional(rollbackFor = { Exception.class })
    public CommonResult addTp(@RequestBody Tp tp) {
        Date date = new Date();
        logger.info("添加溯源模板");
        tp.setCreateTime(date);
        tp.setUpdateTime(date);
        boolean insert = tp.insert();
        if (!insert){
            return CommonResult.failed(ResultCode.INTERNAL_SERVER_ERROR);
        }

        for (TpNode node : tp.getNodeList()) {

            node.setCreateTime(date);
            node.setUpdateTime(date);
            //添加环节表
            node.insert();
            //添加中间表
            Tn tn=new Tn();
            tn.setId(0);
            tn.setLId(node.getId());
            tn.setTId(tp.getId());
            tn.setCreateTime(date);
            tn.setUpdateTime(date);
            tn.insert();
        }

        return new CommonResult(200,"创建成功",tp.getId());
    }
    @ApiOperation("根据角色id查询用户")
    @ResponseBody
    @RequestMapping(value = "/queryUserOne/{rId}",method = RequestMethod.GET)
    public CommonResult selectUserOne(@PathVariable("rId") Integer rId) {
        Qy qy=new Qy();
        QueryWrapper<Qy> wrapper = new QueryWrapper<>();
        wrapper.eq("r_id", rId);
        List<Qy> qies = qy.selectList(wrapper);
        for (Qy qy1:qies){
            qy1.setMm("");
        }
        return new CommonResult(200,"查询成功",qies);
    }
    @ApiOperation("根据模板id查询模板信息")
    @ResponseBody
    @RequestMapping(value = "/queryTpByid/{tId}",produces = "application/json;charset=utf-8",method = RequestMethod.GET)
    public CommonResult queryTpByid(@PathVariable("tId") Integer tId) {
        Tp tp = tpService.queryTpByid(tId);
        return new CommonResult(200,"查询成功",tp);
    }

    @RequestMapping(value = "/updateNode/{nodeId}", produces = "application/json;charset=utf-8",method = RequestMethod.POST)
    @ApiOperation("更新环节状态")
    @ResponseBody
    public CommonResult updateNode(@PathVariable("nodeId") Integer nodeId) {
       TpNode tpNode=new TpNode();
        TpNode tpNode1 = tpNode.selectById(nodeId);
        if (tpNode1 == null){
            return new CommonResult(500,"没有找到该环节","");
        }
        if (tpNode1.getState() != 0){
            return new CommonResult(500,"该环节已经不能继续操作","");
        }
        Tn tn=new Tn();
        QueryWrapper<Tn> wrapper = new QueryWrapper<>();
        wrapper.eq("l_id", nodeId);
        Tn tn1 = tn.selectOne(wrapper);
        if (tn1 == null){
            return new CommonResult(500,"更新环节状态失败","");
        }

        Tp tp = tpService.queryTpByid(tn1.getTId());
        //获取该所有环节
        List<TpNode> nodeList = tp.getNodeList();
        int size = nodeList.size()-1;
        for (int i=0;i <= size;i++){
            //如果找到该节点id
            if (nodeList.get(i).getId().equals(nodeId)){
                int index = i-1;
               if(index >= 0 && index < size){

                   Integer state = nodeList.get(index).getState();
                   if (!state.equals(1)){
                       return new CommonResult(501,"没有走到该环节,不能更新环节状态","");
                   }
               }
               break;
            }
        }

        tpNode1.setState(1);
        String sha256String = SHA256Util.getSHA256String(tpNode1.hashCode() + "");
        tpNode1.setHash(sha256String);
        tpNode1.updateById();
        return new CommonResult(200,"更新环节状态成功","");
    }

       @ApiOperation("根据农产品id查询模板信息")
       @ResponseBody
       @RequestMapping(value = "/queryNcpByid/{nId}",method = RequestMethod.GET)
       public CommonResult queryNcpByid(@PathVariable("nId") String nId) {
           Ncp ncp = tpService.queryNcpByid(nId);
           return new CommonResult(200,"查询成功",ncp);
       }

    @ApiOperation("查询运输商可以管理的环节,state为-1查找全部")
    @ResponseBody
    @RequestMapping(value = "/queryNodeByQy/{qyid}/{state}/{rId}",method = RequestMethod.GET)
    public CommonResult queryNodeByQy(@PathVariable("qyid") String qyid,@PathVariable("state") Integer state,@PathVariable("rId")int rId) {
        Qy qy=new Qy();
        QueryWrapper<Qy> wrapper = new QueryWrapper<>();
        wrapper.eq("qyid", qyid);
        Qy qy1 = qy.selectOne(wrapper);
        if (qy1 != null){
            Integer rId2 = qy1.getRId();
            if (!rId2.equals(rId)){
                return new CommonResult(500,"角色不匹配","");
            }
        }
        List<NodeInfo>  nodeInfo = tpService.queryNodeByQy(qyid,state);
        return new CommonResult(200,"查询成功",nodeInfo);
    }


    @ApiOperation("查询状态为0的可用溯源模板")
    @ResponseBody
    @RequestMapping(value = "/queryTPByState",method = RequestMethod.GET)
    public CommonResult queryTPByState() {
        Tp tp=new Tp();
        QueryWrapper<Tp> wrapper = new QueryWrapper<>();
        wrapper.eq("state", 0).eq("type",0);
        List<Tp> tps = tp.selectList(wrapper);
        return new CommonResult(200,"查询成功",tps);
    }

    @ApiOperation("查询所有可用模板信息")
    @ResponseBody
    @RequestMapping(value = "/queryTpAll/{qyid}",method = RequestMethod.GET)
    public CommonResult selectTp(@PathVariable("qyid") String qyid) {
        Tp tp=new Tp();
        QueryWrapper<Tp> wrapper = new QueryWrapper<>();
        wrapper.eq("qyid", qyid).eq("type",0);;
        wrapper.ne("state", 2);
        List<Tp> tps = tp.selectList(wrapper);
        //倒序
        Collections.reverse(tps);
        return new CommonResult(200,"查询成功",tps);
    }
    @ApiOperation("删除模板信息")
    @ResponseBody
    @RequestMapping(value = "/deleteTpById/{tId}",method = RequestMethod.POST)
    public CommonResult selectTp(@PathVariable("tId")Integer tId) {
        Tp tp=new Tp();
        Tp tp1 = tp.selectById(tId);
            if (tp1 == null){
            return new CommonResult(500,"没有找到该模板","");
        }
        if(tp1.getState().equals(2)){
            return new CommonResult(500,"不能重复删除","");
        }
        tp1.setState(2);
        tp1.updateById();
        return new CommonResult(200,"删除成功","");
    }

    @ApiOperation("查询最新的农产品信息")
    @ResponseBody
    @RequestMapping(value = "/queryNewNcp",method = RequestMethod.GET)
    public CommonResult queryNewNcp() {
        Ncp ncp=new Ncp();
        QueryWrapper<Ncp> wrapper = new QueryWrapper<>();
        wrapper.ne("state", 1);
        List<Ncp> tps = ncp.selectList(wrapper);
        if (tps.size()>0){
            //倒序
            Collections.reverse(tps);
            return new CommonResult(200,"查询成功",tps.get(0));
        }

        return new CommonResult(500,"没有查询到数据","");
    }


    @ApiOperation("根据角色id查询所有企业")
    @ResponseBody
    @RequestMapping(value = "/queryQyAll/{rId}",method = RequestMethod.GET)
    public CommonResult queryQyAll(@PathVariable("rId")Integer rId) {
        Qy qy=new Qy();
        QueryWrapper<Qy> wrapper = new QueryWrapper<>();
        if(!rId.equals(-1)){
            wrapper.eq("r_id",rId);
        }
        wrapper.ne("state", 1);
        List<Qy> tps = qy.selectList(wrapper);
        return new CommonResult(200,"查询成功",tps);
    }
    @ApiOperation("根据企业id更新信息")
    @ResponseBody
    @RequestMapping(value = "/updateQy",method = RequestMethod.POST)
    public CommonResult updateQy(@RequestBody Qy qy) {
        QueryWrapper<Qy> wrapper = new QueryWrapper<>();
        wrapper.eq("qyid",qy.getQyid());
        boolean update = qy.update(wrapper);
        if (!update){
            return new CommonResult(500,"更新失败","");
        }
        return new CommonResult(200,"更新成功","");
    }
    @ApiOperation("根据企业id删除企业")
    @ResponseBody
    @RequestMapping(value = "/deleteQyById/{qyid}",method = RequestMethod.POST)
    public CommonResult deleteQyByQid(@PathVariable("qyid") String qyid) {
        Qy qy=new Qy();
        QueryWrapper<Qy> wrapper = new QueryWrapper<>();
        wrapper.eq("qyid",qyid);
        Qy qy1 = qy.selectOne(wrapper);
        if (qy1 == null){
            return new CommonResult(500,"删除失败","");
        }
        qy1.setState(1);
        boolean update = qy1.update(wrapper);
        if (!update){
            return new CommonResult(500,"删除失败","");
        }
        return new CommonResult(200,"删除成功","");
    }
}
